<template>
	<div>
		<a-table bordered :columns="managerOrFinance() ? columns : columns1" :data-source="bom.bomMaterials"
			 :pagination="false">

			<!-- <span slot="image" slot-scope="text">
				<image-preview :images="text" />
			</span> -->
			<span slot="image" slot-scope="text,record">				
				<image-preview1 :images="text" :imageUrl="record.imageUrl" />
			</span>

			<template slot="title" slot-scope="currentPageData">
				<span>{{ bom.bomName }}</span>
				<span style="float: right">
					<a @click="deleteTable" v-show="(!readonly && allowDeleteBom) || isPermission">删除</a>
					<span v-if="managerOrFinance()">合计:</span>
					<span v-if="managerOrFinance()" style="color: red">¥{{ sumPrice }}</span>
				</span>
			</template>

			<span slot="materialCode" slot-scope="text, record, index">
				<a-button v-if="record.editable" type="dashed" @click="handleEmsMaterialIndex1Show(record)">
					{{ record.materialCode || '选择原料' }}
				</a-button>
				<template v-else>
					{{ record.materialCode || '选择原料' }}
				</template>
			</span>

			<span slot="number" slot-scope="text, record, index">
				<template v-if="record.editable">
					<a-input-number v-model:value="record.materialNumber" :step="0.01" @blur="inputNumerBlur(record)" :min="0" style="width: 100%;" />
				</template>
				<template v-else>
					{{ text }}
				</template>
			</span>
			<span slot="classGroupId" slot-scope="text, record, index">								
				<a-select v-model="record.classGroupId" :disabled="!record.editable">
					<a-select-option :value="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
						{{ item.name }}
					</a-select-option>
				</a-select>
			</span>

			<template slot="operation-title">
				<span>操作</span>
				<a-button type="primary" @click="addRow" style="margin-left: 20px" v-show="!readonly || isPermission">
					新增
				</a-button>
			</template>

			<template slot="operation" slot-scope="text, record, index">
				<div class="editable-row-operations" v-show="!readonly || isPermission">
					<span v-if="record.editable">
						<a @click="save(record.key)">保存</a>
						<a @click="cancel(record.key)" style="margin-left: 20px;">取消</a>
					</span>
					<span v-else v-show="!readonly || isPermission">
						<a @click="edit(record.key)">修改</a>
						<a @click="deleteRow(record.key)" style="margin-left: 20px;">删除</a>
					</span>
				</div>
			</template>
		</a-table>
		<ems-material-index1 ref="emsMaterialIndex1" :on-row-selected="onEmsMaterialIndex1Selected" />
	</div>
</template>

<script>
import emsMaterialIndex1 from '../emsmaterial/emsMaterialIndex1'
import { MATERIAL_TYPE_ENUM } from '@/utils/util'

import { page as teamPage } from '@/api/modular/main/classGroup/classGroup'

function emptyBomMaterial() {
	return {
		key: '',
		bomMaterialId: '',
		bomId: '',
		bomIdSource: '',
		bomMaterialSort: '',
		materialId: '',
		materialNumber: '',
		createTime: '',
		createUser: '',
		updateTime: '',
		updateUser: '',
		classGroupId:''
	}
}

export default {
	name: 'FCBomMaterialTable',
	components: {
		emsMaterialIndex1
	},
	props: {
		// 以后直接传BOM对象过来,方便显示头部和区别相同的BOM
		readonly: false,
		isPermission: false,
		defaultBom: {},
		data: {
			type: Array
		},
		typeDictTypeDropDown: {},
		allowDeleteBom: {
			type: Boolean,
			default: true
		}
	},
	data: function () {
		return {
			bom: {
				bomId: '',
				bomCode: '',
				bomName: '',
				bomType: '',
				status: '',
				image: '',
				materialModelNumber: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				bomMaterials: [],
				otherBoms: [],
			},
			// dataSource: [],
			cacheData: [],
			keyCount: 0,
			editingKey: '',
			editingRow: null,
			columns: [
				{
					title: '序号',
					width: '80px',
					dataIndex: 'index',
					key: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '类型',
					dataIndex: 'type',
					key: 'type',
					width: 100,
					ellipsis: true,
					customRender: (text, record, index) => `${this.$util.findMaterialTypeById(record.materialType)?.name || ''}`
				},
				{
					title: '料号',
					dataIndex: 'materialCode',
					key: 'materialCode',
					scopedSlots: { customRender: 'materialCode' },
					width: 190
				},
				{
					title: '名称',
					dataIndex: 'materialName',
					key: 'materialName',
					// ellipsis: true,
					width: 180,
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber',
					key: 'materialModelNumber',
					width: 130,
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' },
					width: 100,
				},
				{
					title: '领用方',
					dataIndex: 'classGroupId',
					width: 120,
					scopedSlots: { customRender: 'classGroupId' }
				},
				{
					title: '数量',
					dataIndex: 'materialNumber',
					key: 'materialNumber',
					width: 100,
					scopedSlots: { customRender: 'number' }
				},
				{
					title: '成本',
					dataIndex: 'costPrice',
					key: 'costPrice',
					width: 70,
					ellipsis: true,
				},

				{
					key: 'action',
					width: '180px',
					// fixed:'right',
					// align:'center',
					slots: { title: 'operation-title' },
					scopedSlots: { customRender: 'operation' }
				}
			],
			columns1: [
				{
					title: '序号',
					width: '80px',
					dataIndex: 'index',
					key: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '料号',
					dataIndex: 'materialCode',
					key: 'materialCode',
					scopedSlots: { customRender: 'materialCode' },
					width: 130
				},
				{
					title: '名称',
					dataIndex: 'materialName',
					key: 'materialName',
					// ellipsis: true,
					width: 180,
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' },
					width: 100,
				},
				
				{
					title: '数量',
					dataIndex: 'materialNumber',
					key: 'materialNumber',
					width: 120,
					scopedSlots: { customRender: 'number' }
				},
				{
					title: '类型',
					dataIndex: 'type',
					key: 'type',
					width: 120,
					ellipsis: true,
					customRender: (text, record, index) => `${this.$util.findMaterialTypeById(record.materialType)?.name || ''}`
				},
				{
					title: '领用方',
					dataIndex: 'classGroupId',
					width: 120,
					scopedSlots: { customRender: 'classGroupId' }
				},
				{
					key: 'action',
					width: '180px',
					// align:'center',
					// fixed:'right',
					slots: { title: 'operation-title' },
					scopedSlots: { customRender: 'operation' }
				}
			],
			teamList: [],
		}
	},
	computed: {
		sumPrice() {
			let sum = 0
			for (const bomMaterial of this.cacheData) {
				sum += bomMaterial.costPrice * bomMaterial.materialNumber
			}
			if (isNaN(sum)) {
				return '-'
			}
			return sum.toFixed(2)
		}
	},
	created() {
		this.getTeamList();
		console.log("进入");
		
		if (this.defaultBom) {
			this.bom = Object.assign({}, this.defaultBom, { bomMaterials: [...this.defaultBom.bomMaterials] })
			for (const bomMaterial of this.bom.bomMaterials) {
				if (!bomMaterial.key) {
					bomMaterial.key = bomMaterial.bomMaterialId
				}
			}
			// this.dataSource = this.bom.bomMaterials
			this.cacheData = [...this.bom.bomMaterials]
			this.keyCount = this.bom.bomMaterials.length
		}
		
	},
	watch: {
		defaultBom(newValue) {
			this.bom = Object.assign({}, this.defaultBom, { bomMaterials: [...this.defaultBom.bomMaterials] })
			for (const bomMaterial of this.bom.bomMaterials) {
				if (!bomMaterial.key) {
					bomMaterial.key = bomMaterial.bomMaterialId
				}
			}
			// this.dataSource = this.bom.bomMaterials
			this.cacheData = [...this.bom.bomMaterials]
			this.keyCount = this.bom.bomMaterials.length
		}
	},
	methods: {
		handleChange(value, key, column) {
			const newData = [...this.data]
			const target = newData.filter(item => key === item.key)[0]
			if (target) {
				target[column] = value
				this.data = newData
			}
		},
		inputNumerBlur(record){
			console.log(record.materialNumber);
			if(record.materialNumber == null){
				record.materialNumber = 1;
			}else{
				record.materialNumber = record.materialNumber.toFixed(2);
			}
		},
		/**
		 * 获取领用方
		 */
		getTeamList() {
			teamPage({
				pageSize: -1,
				status: 0
			}).then(res => {
				this.teamList = res.data.rows;
			})
		},
		addRow() {
			let key = this.keyCount++
			this.editingKey = key
			this.bom.bomMaterials.push(Object.assign(emptyBomMaterial(), {
				key: key,
				bomIdSource: this.bom.bomId,
				editable: true
			}))
			this.cacheData.push(Object.assign(emptyBomMaterial(), { key: key, bomIdSource: this.bom.bomId }))
		},
		deleteRow(key) {
			let start = 0
			let deleteCount = 1
			start = this.bom.bomMaterials.findIndex(item => item.key == key)
			this.bom.bomMaterials.splice(start, deleteCount)
			this.cacheData.splice(start, deleteCount)
		},
		edit(key) {
			const newData = [...this.bom.bomMaterials]
			const target = newData.filter(item => key === item.key)[0]
			this.editingKey = key
			if (target) {
				target.editable = true
				this.bom.bomMaterials = newData
			}
		},
		save(key) {
			const newData = [...this.bom.bomMaterials]
			const newCacheData = [...this.cacheData]
			const target = newData.filter(item => key === item.key)[0]
			const targetCache = newCacheData.filter(item => key === item.key)[0]

			// 还需要判断控件里面是否都填入的值,不然不可以保存
			if (!target.materialId) {
				console.error(`物料必选`)
				this.$message.error('物料必选')
				return
			}
			if (!target.materialNumber) {
				console.error(`数量必选`)
				this.$message.error('数量必选')
				return
			}

			if (target && targetCache) {
				delete target.editable
				this.bom.bomMaterials = newData
				Object.assign(targetCache, target)
				this.cacheData = newCacheData
			}
			this.editingKey = ''
		},
		cancel(key) {
			const newData = [...this.bom.bomMaterials]
			const target = newData.filter(item => key === item.key)[0]
			this.editingKey = ''
			if (target) {
				let cacheData = this.cacheData.filter(item => key === item.key)[0]
				if (cacheData.materialId) {
					Object.assign(target, cacheData)
					delete target.editable
				} else {
					let number = newData.indexOf(target)
					newData.splice(number, 1)
					this.cacheData.splice(number, 1)
				}
				this.bom.bomMaterials = newData
			}
		},
		getTableValue() {
			return this.bom.bomMaterials
		},
		getBom() {
			return this.bom
		},
		handleEmsMaterialIndex1Show(row) {
			this.editingRow = row
			console.log('row', row)
			let materialType = this.$businessEnum.MATERIAL_TYPE_ENUM.material.id
			let materialTypeList = [
				this.$businessEnum.MATERIAL_TYPE_ENUM.material,
				this.$businessEnum.MATERIAL_TYPE_ENUM.customized,
				this.$businessEnum.MATERIAL_TYPE_ENUM.cable,
			]
			this.$refs.emsMaterialIndex1.show({ materialType, materialTypeList })
		},
		onEmsMaterialIndex1Selected(materialRow) {
			console.log('row......', materialRow)
			// console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
			let { materialId, materialName, materialCode, materialType, costPrice, image, materialModelNumber,classGroupId,imageUrl } = materialRow
			this.editingRow = Object.assign(this.editingRow, {
				materialId,
				materialName,
				materialCode,
				materialType,
				costPrice,
				image,
				imageUrl,
				materialModelNumber,
				classGroupId
			})
			this.bom.bomMaterials = [...this.bom.bomMaterials]
		},
		deleteTable() {
			let key = this.$vnode.key
			this.$emit('delete', key)
		},


	}
}
</script>
<style scoped>
.ant-table-title {
	height: 55px;
}
</style>